package me.ezitku.base.ScreenRecord

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.media.ImageReader
import com.ug_project.Async.runASync
import com.ug_project.system.nowTimeString
import me.ezitku.base.extensions.displayHeight
import me.ezitku.base.extensions.displayWidth
import me.ezitku.base.extensions.screenCapturePath
import me.ezitku.base.extensions.writeBitmap
import java.io.File


/**
 * ئېكراننى رەسىمگە تۇتۇش
 * بۇ فونكىسسيە چوقۇم onActivityResult نىڭ ئىچىدە ئىجرا بولىىش كېرەك
 */
fun Activity.screenCapture(requestCode: Int, resultCode: Int, resultData: Intent, REQUEST_CODE: Int,
                           action: (ScreenCaptureConfig.() -> Unit)? = null) {
    if (requestCode == REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            var config = ScreenCaptureConfig()
            action?.invoke(config)
            var imageReader = ImageReader.newInstance(displayWidth, displayHeight, PixelFormat.RGBA_8888, 2)
            createMediaProjection(resultCode, resultData)?.createVirtualDisplay("screen-mirror",
                    displayWidth, displayHeight, 1, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                    imageReader.surface, null, null)

            runASync {
                delay(300)
                val image = imageReader.acquireLatestImage()

                val width = image.width
                val height = image.height
                val planes = image.planes
                val buffer = planes[0].buffer
                //每个像素的间距
                val pixelStride = planes[0].pixelStride
                //总的间距
                val rowStride = planes[0].rowStride
                val rowPadding = rowStride - pixelStride * width
                var bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888)
                bitmap.copyPixelsFromBuffer(buffer)
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height)
                image.close()

                File(config.savePath).writeBitmap(bitmap)
            }
        }
    }
}


class ScreenCaptureConfig {
    /**
     * رەسىمنىڭ ساقلايدىغان ئورنى
     */
    var savePath = screenCapturePath + nowTimeString("yyyy-MM-dd-HH-mm-ss")
}


